import React from 'react';
import { Result, Button } from 'antd';

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null, errorInfo: null };
  }

  static getDerivedStateFromError(error) {
    // 更新状态以显示错误UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // 记录错误信息
    console.error('ErrorBoundary caught an error:', error, errorInfo);
    this.setState({
      error,
      errorInfo
    });
  }

  render() {
    if (this.state.hasError) {
      return (
        <Result
          status="500"
          title="页面渲染出错"
          subTitle="抱歉，页面出现了错误。请检查浏览器控制台获取详细信息。"
          extra={
            <div>
              <Button type="primary" onClick={() => window.location.reload()}>
                刷新页面
              </Button>
              <div style={{ marginTop: 16, textAlign: 'left', fontSize: '12px', color: '#666' }}>
                <details>
                  <summary>错误详情</summary>
                  <pre style={{ whiteSpace: 'pre-wrap' }}>
                    {this.state.error && this.state.error.toString()}
                    <br />
                    {this.state.errorInfo.componentStack}
                  </pre>
                </details>
              </div>
            </div>
          }
        />
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;